import { updateUserIdCard } from '../../../api/user'
import { uploadFileName, wxUpload } from '../../../utils/upload'

Page({
  data: {
    idcardFrontUrls: [],
    idcardBackUrls: [],

    idcard: {
      idcardNumber: '',
      realName: '',
      idcardFrontUrl: '',
      idcardBackUrl: ''
    }
  },

  onLoad: function (options) {
    this.setData({
      idcard: getApp().globalData.idCard,
      idcardFrontUrls: [{url: getApp().globalData.idCard.idcardFrontUrl}],
      idcardBackUrls: [{url: getApp().globalData.idCard.idcardBackUrl}],
    })
  },

  editIdcardNumber(e) {
    this.setData({
      'idcard.idcardNumber': e.detail.value
    })
  },

  editRealName(e) {
    this.setData({
      'idcard.realName': e.detail.value
    })
  },

  afterRead(event) {
    const _this = this;
    const { file } = event.detail;
    const fileName = uploadFileName(file.path);
    const name = event.currentTarget.dataset.name;

    wxUpload({
      biz: 'CERTIFICATE',
      fileName: fileName,
      size: file.size,
      filePath: file.path
    }).then(res => {
      switch (name) {
        case 'idcardFront':
          _this.setData({
            idcardFrontUrls: [{url: res.signatureUrl}],
            'idcard.idcardFrontUrl': res.uri
          })
          break;
        case 'idcardBack':
          _this.setData({
            idcardBackUrls: [{url: res.signatureUrl}],
            'idcard.idcardBackUrl': res.uri
          })
          break;
      }
    })
  },

  removeImage(e) {
    const name = e.currentTarget.dataset.name;
    switch(name) {
      case 'idcardFront':
        this.setData({
          idcardFrontUrls: [],
          'idcard.idcardFrontUrl': ''
        })
        break;
      case 'idcardBack':
        this.setData({
          idcardBackUrls: [],
          'idcard.idcardBackUrl': ''
        })
        break;
    }
  },

  done(e) {
    updateUserIdCard(this.data.idcard).then(res => {
      wx.navigateBack({
        delta: 1,
      })
    })
  }

})
